package org.lee.jfc.web;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * ShowChart
 * servlet显示图
 * @author dralee
 * @date 2021-12-29 15:39:07
 **/
@WebServlet(name = "showChat", urlPatterns = {"/showChart"})
public class ShowChart extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/png");
        try(OutputStream outputStream = resp.getOutputStream()){
            JFreeChart chart = getChart();
            int width = 500;
            int height = 350;
            ChartUtils.writeChartAsPNG(outputStream, chart, width, height);
        }
    }

    private JFreeChart getChart() {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue("Croatia", 22);
        dataset.setValue("Bohemia", 34);
        dataset.setValue("Bulgaria", 18);
        dataset.setValue("Spain", 5);
        dataset.setValue("Others", 21);

        JFreeChart chart = ChartFactory.createPieChart("Popular destinations",
                dataset, true, false, false);

        chart.setBorderVisible(false);
        return chart;
    }
}
